package com.iflytek.tts.TtsService;

import java.io.File;
import java.util.PriorityQueue;
import java.util.Queue;

import com.astrob.naviframe.Start;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Process;


import android.util.Log;
import com.astrob.tts.BaiduTTS;

public class TtsSpeaker implements Runnable {
	private static final String TAG = "TtsSpeaker";
	private static TtsSpeaker instance;
	private boolean bStop;
	private Queue<String> voiceQueue;
	private boolean bMute;

	private TtsSpeaker() {
		//Process.setThreadPriority(0);
		bMute = false;
		voiceQueue = new PriorityQueue<String>();
		Thread a = new Thread(this, TAG);
		a.setPriority(Thread.MAX_PRIORITY); // 10 
		a.start();
	}
	private boolean hasInited = false;
	public boolean init(String resourcePath){
		try {
			File f = new File(resourcePath);
			if(f.exists()){
				hasInited = true;
				Tts.JniInit(resourcePath);
				return true;
			}
		} catch (Exception e) {

		}
		return false;
//		return true;
	}
	public static TtsSpeaker getInstance() {
		if (instance == null) {
			synchronized (TtsSpeaker.class) {
				if (instance == null) {
					instance = new TtsSpeaker();
				}
			}
		}
		return instance;
	}
	private void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 以异步方式播放
	 */
	public void talk(String text) {
		text = text.replace("华", "滑");
		text = text.replace("都", "督");
		text = text.replace("陂", "陂[=pi2]");
		text = text.replace("翟", "翟[=di2]");
		text = text.replace("莘", "莘[=xin1]");

		text = text.replace(" I,", " 1,");
		text = text.replace(" II,", " 2,");
		text = text.replace(" III,", " 3,");
		text = text.replace(" IV,", " 4,");
		text = text.replace(" V,", " 5,");
		text = text.replace(" VI,", " 6,");
		text = text.replace(" VII,", " 7,");
		text = text.replace(" VIII,", " 8,");
		text = text.replace(" IX,", " 9,");
		text = text.replace(" X,", " 十,");

		text = text.replace("500", "五百");
		text = text.replace("100", "一百");
		text = text.replace("50", "五十");

		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH) {
			//4.4一下系统使用，5.0可能也可以(6.0应该不可以)，华测设备为4.4
			talk(text, false);
		} else {
			BaiduTTS.speak(text);
		}

	}

	public void postToWorkQueue(String text) {
		// if (StringUtil.isEmpty(text))
		// return;
		if (text == null || text.length() == 0)
			return;
		synchronized (voiceQueue) {
			voiceQueue.clear();
			voiceQueue.offer(text);
		}
	}

	/**
	 * 
	 * @param text
	 *            播报内容
	 * @param bSyc
	 *            bSyc = true, 以同步方式播放 bSyc = false, 以异步方式播放
	 */
	public void talk(String text, boolean bSyc) {
		// if (StringUtil.isEmpty(text))
		if (text == null || text.length() == 0)
			return;
		if (isCalling()) {
			return;
		}
		if (bMute) {
			return;
		}
		
		if (bSyc) {
			if (1 == AudioData.mAudioLifecycleType) {
				AudioData.palyAudioTrack();
			}
			try {
				if(hasInited){
					Tts.JniSpeak(text);
				}
			} catch (Exception e) {
				return;
			}

		} else {
			postToWorkQueue(text);
		}
	}

	private boolean HaveUnHandlerEvent() {
		return !voiceQueue.isEmpty();
	}

	private void HandlePostEvent() {
		int nSize = 5;
		while (voiceQueue.isEmpty() == false && nSize > 0) {
			String voice = null;
			synchronized (voiceQueue) {
				voice = voiceQueue.poll();
			}

			talk(voice, true);// 同步播报
			--nSize;
		}
	}

	@Override
	public void run() {
		// Changes the Priority of the calling Thread!
		//Process.setThreadPriority(-10);
		// Changes the Priority of passed Thread (first param)  range 的范围是 -20 (高) 到 +19 (低)
		//Process.setThreadPriority(Process.myTid(), -18);

		while (!bStop) {
			if (HaveUnHandlerEvent()) {
				setBusy(true);
				HandlePostEvent();
				sleep(100);
			} else {
				sleep(100);
				setBusy(false);
			}
		}
	}

	public synchronized void setBusy(boolean busy) {
		if (mBusy && !busy) {
			//从busy 到 非 busy，表播报结束
			if (1 == AudioData.mAudioLifecycleType) {
				//AudioData.releaseAudioTrack();
				AudioData.stopAudioTrack();
			}
			//mMsgHandler.sendEmptyMessage(2);
		}
		mBusy = busy;
	}

	public synchronized boolean isBusy() {
		return mBusy;
	}

	private boolean mBusy = false;

	public void stop() {
		bStop = true;
//		BaiduTTS.stop();
	}

	public void stopCurrentVoice() {
		if(hasInited){
			Tts.JniStop();
		}
//		BaiduTTS.stop();
	}

	public static final int CHINESE = 8;
	public static final int YUEYU = 11;

	public void setLanguage(int nLang) {
		if (nLang != CHINESE && nLang != YUEYU) {
			Log.e("TTS", "set Language param error");
			return;
		}
		if(hasInited){
			Tts.JniSetLanguage(nLang);
		}
	}

	private boolean mIsCalling = false;

	public void setCalling(boolean bCalling) {
		mIsCalling = bCalling;
	}

	private boolean isCalling() {
		return mIsCalling;
	}
	
	public void setTTSMute(boolean isMute) 
	{
		bMute = isMute;
		if (bMute) {
			stopCurrentVoice();
		}
	}
}
